<template>
  <div class="views_trend">
    <p class="title">趋势分析</p>
    <div class="form_search">
      <el-form>
        <el-select v-model="cycle" placeholder="周期" class="cycle" @change="changeCycle">
          <el-option v-for="item in cycleList" :key="item.value" :value="item" :label="item.label"></el-option>
        </el-select>
        <div class="createTime timePicker" style="width: 100%">
          <el-input v-if="dateType !== 'yearrange' && dateType !== 'quartrange'" v-model="form.local_time.value"  placeholder="选择日期"></el-input>
          <el-date-picker  @change="changeTime"  v-model="timePicker" :pickerOptions="pickerOptions"
            :type="dateType" range-separator="-"   prefix-icon="0" start-placeholder="开始日期"
          :value-format="timeFormat" end-placeholder="结束日期" placeholder="选择日期"></el-date-picker>
        </div>
      </el-form>
      <div class="form_btn">
        <el-button type="search" icon="iconfont icon-search_normal" @click="getData"></el-button>
        <el-button  icon="iconfont icon-Refresh" @click="resetForm"></el-button>
      </div>
    </div>
    <div id="charts_views_trend" :style="'height:' + chartsH + 'px'"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { mapGetters } from 'vuex'
import { viewTrend } from '@/api/kanban/index.js'
import { setSearchParams, timeTransfor, setEchartsOptionsDatazoom, timeFormat,transforTime, setPickerOptions ,setEchartsBarwidth, setEchartsTooltip } from '@/utils/index.js'
export default {
  data () {
    return {
      timePicker: '',
      dateType: 'daterange',
      timeFormat: 'yyyy-MM-dd',
      cycle: '日',
      form: {
        local_time: { value: '', op: 'RANGE' },
      },
      cycleList: [ //周期下拉框
        { value: '日', label: '日', type: 'daterange' },
        { value: '月', label: '月', type: 'monthrange' },
        { value: '季', label: '季', type: 'quartrange' },
        { value: '年', label: '年', type: 'yearrange' },
      ],
      siteList: [],
      seriesData: [],
      xAxis: [],
      start_date:'',
      end_date: '',
      loading:  false,
      chart: null,
      pickerOptions: setPickerOptions(),
      chartsH: ''
    }
  },
  props: ['show'],
  computed: {
    ...mapGetters(['sidebar', ]),
    isCollapse(){
      return !this.sidebar.opened
    }
  },
  watch: {
    show: function() {
      if(this.show) {
        this.getData()
        this.setHeight()
      }
    },
    isCollapse: function () {
      this.drawEcharts()
    }
  },
  created () {
    if(this.show) {
      this.getData()
    } 
    this.setDateCur()
  },
  mounted () {
    this.setHeight()
  },
  methods: {
    setHeight () { //图表高度
      this.$nextTick(()=>{ 
        let dom = document.getElementsByClassName("kanban_views")[0].offsetHeight
        let title = document.getElementsByClassName("kanban_views")[0].getElementsByClassName('views_left')[0].getElementsByClassName('title')[0].offsetHeight
        let form =  document.getElementsByClassName("kanban_views")[0].getElementsByClassName('views_left')[0].getElementsByClassName('form_search')[0].offsetHeight
        this.chartsH = dom - title - form - 32 - 33
      })
    },
    setDateCur() {  // 初始化设置默认日期 30天
      let date1 = timeFormat(new Date()).split(' ')[0]
      let date2 = timeFormat(new Date(new Date().getTime() - 30*24*60*60*1000)).split(' ')[0]
      this.timePicker = [date2, date1]
      let obj = timeTransfor(this.timePicker,  this.cycle)
      this.form.local_time.value = obj.start_date + ' - '+ obj.end_date
      this.start_date = obj.start_date
      this.end_date =  obj.end_date  
    },
    changeCycle (item) {
      this.form.local_time.value  = null
      this.start_date = ''
      this.end_date =  ''
      this.timePicker = null
      this.dateType = item.type
      this.cycle = item.value
      // this.getData()
    },
    changeTime (arr) { //时间选择
      if(arr) {
        let obj = timeTransfor(arr,  this.cycle)
        this.form.local_time.value = obj.start_date + ' - '+ obj.end_date
        this.start_date = obj.start_date
        this.end_date =  obj.end_date  
      } else {
        this.form.local_time.value  = null
        this.start_date = ''
        this.end_date =  ''
      }
      this.getData()
    },
    // 堆叠图柱状图
    drawEcharts () {
      if(this.chart) {
        this.chart.dispose()
      }
      let dom = document.getElementById('charts_views_trend');
      this.chart = echarts.init(dom);
      let option = {
        tooltip: setEchartsTooltip(0, true),
        legend: {
          data: this.legendData,
          bottom: 24,
        },
        color: ['#4AB2FF', '#B1E7CB', '#FFD0CD', '#FFE2BE', '#F7748C', '#A2CBEF', '#9BA5E6', '#FFB385', '#EA9898'],
        grid: {
          left: '0%',
          right: '0%',
          top: '2%',
          bottom: 64,
          containLabel: true,
        },
        xAxis: [
          {
            type: 'category',
            data:  this.xAxis, 
            axisPointer: {
              type: 'shadow',
              shadowStyle: {
                color: 'rgba(235, 234, 234, 0.4)'
              }
            },
            axisTick: {
              alignWithLabel: true
            },
            axisLine: {
              onZero : false,
              lineStyle:{
                color: '#666666'
              }
            },
          }
        ],
        yAxis: [
          { 
            type: 'value' ,
            splitLine: {
              lineStyle: {
                color: '#EBEAEA'
              }
            },
             axisLine: {
               show: false
             },
             axisTick: {
               show: false
             }
            
          }
        ],
        series: this.seriesData,
        dataZoom: setEchartsOptionsDatazoom(this.cycle, this.xAxis),
        animationDuration: 1500
      };
      this.chart.setOption(option);

    },
    //数据获取
    getData() {
      if(!this.loading) {
        let params = setSearchParams(this.form)
        params.start_date = this.start_date
        params.end_date = this.end_date
        params.cycle = this.cycle
        this.loading = true
        this.legendData = []
        this.xAxis = [] 
        this.seriesData = []
        viewTrend(params).then(res=>{
          if(res.state == 1) {
            let data = res.data
            for(let item in data){
              this.legendData.push(item)
              let obj = {name: item, type: 'bar', stack: '趋势分析', barWidth: '70%', data: [] }
              
              let dataArr = []
              for(let i in data[item]) {
                dataArr.push(data[item][i])
                if(this.xAxis.indexOf(i) == -1) {
                  this.xAxis.push(i)
                }
              }
              obj = setEchartsBarwidth(obj, params.cycle,this.xAxis.length )
              obj.data = dataArr
              this.seriesData.push(obj)
            }
            this.xAxis = transforTime(this.xAxis, this.cycle) // 横轴格式转换
            this.drawEcharts()
          }
         
          this.loading = false
        })
      
      }

    },
    // 重置按钮
    resetForm(){
      for(let item in this.form){
        this.form[item].value =""
      }
      this.cycle = '日'
      this.setDateCur()
      this.getData()
    },
  }

}
</script>

<style lang="scss">

</style>